package com.atguigu.search;

/**
 * @author RuiKnag
 * @create 2021-05-26-16:55
 */

public class BinarySearchDemo {
    public static void main(String[] args) {
        int[] arr={1,3,8,10,11,67,100};
        int index = binarySearch(arr, 0, arr.length - 1, 7,1);
        System.out.println("index = " + index);
    }
    //使用递归的方式进行遍历
    public static int binarySearch(int[] arr,int left,int right,int findVal){
        if(left>right){
            throw new RuntimeException("没有这个值");
        }
        int mid=left+(right-left)/2;

        if(findVal>arr[mid]){
            return binarySearch(arr, mid + 1, right, findVal);
        }else if(findVal<arr[mid]){
            return binarySearch(arr,left,mid-1,findVal);
        }else{
            return mid;
        }
    }
    //使用非递归的方式查找
    public static int binarySearch(int[] arr,int left,int right,int findVal,int kr){

        while (left<=right){
            int mid=left+(right-left)/2;
            if(findVal>arr[mid]){
                left=mid+1;
            }else if(findVal<arr[mid]){
                right=mid-1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
